<?php
namespace app\api\controller;

use app\common\model\Goods as GoodsModel;
use app\common\model\User as UserModel;
use app\store\model\Setting as SettingModel;
use app\common\extend\Payapi as PayModel;

use think\Request;
use think\Cache;
use think\Db; 
/**
 * 用户控制器
 * Class User
 * @package app\api\controller
 */
class User extends Controller
{
    /**
	 * 用户收货地址列表
	 */
	 public function address() {
		$list = db("user_address")->where(['user_id' => $this->user_info['user_id']])->field("id,name,mobile,province_name,city_name,area_name,address,is_default")->order('id DESC')->paginate(10, false, [
			'query' => Request::instance()->request()
		])->each(function($item , $key){
			$item['address'] = $item['province_name'].$item['city_name'].$item['area_name'].$item['address'];
			unset($item['province_name']);
			unset($item['city_name']);
			unset($item['area_name']);
			return $item;
		})->toArray()['data'];
		return $this->renderSuccess(compact('list'));
	 }
	 
	 /**
	  * 新增收货地址
	  */
	 public function saveaddress() {
		 $id = $this->request->param("id/d" , 0);
		 $name = $this->request->param("name/s" , '');
		 $name ? $name : $this->error('姓名不能为空');
		 $mobile = $this->request->param("mobile/s" , '');
		 $mobile ? $mobile : $this->error('手机号不能为空');
		 $address = $this->request->param("address/s" , '');
		 $address ? $address : $this->error('详细地址不能为空');
		 $province = $this->request->param("province/d" , 0);
		 $province ? $province : $this->error('请选择省');
		 $city = $this->request->param("city/d" , 0);
		 $city ? $city : $this->error('请选择市');
		 $area = $this->request->param("area/d" , 0);
		 $area ? $area : $this->error('请选择区');
		 $is_default = $this->request->param("is_default/d",0);
		 $data = [
			'name' => $name,
			'mobile' => $mobile,
			'address' => $address,
			'province' => $province,
			'city' => $city,
			'area' => $area,
			'is_default' => $is_default,
			'province_name' => db('region')->where(['id' => $province])->value("name"),
			'city_name' => db('region')->where(['id' => $city])->value("name"),
			'area_name' => db('region')->where(['id' => $area])->value("name"),
		 ];
		 if( $id > 0 ) {
			 $result = db("user_address")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->update( $data );
			 if( $result ) {
				 $this->success('修改成功');
			 } else {
				 $this->error('修改失败，请重试');
			 }
		 } else {
			 $data['create_time'] = time();
			 $data['user_id'] = $this->user_info['user_id'];
			 $result = db("user_address")->insert( $data );
			 if( $result ) {
				 $this->success('新增成功');
			 } else {
				 $this->error('新增失败，请重试');
			 }
		 }
	 }
	 
	 /**
	  * 收货地址详情
	  */
	 public function infoaddress() {
		 $id = $this->request->param("id/d" , 0);
		 $info = db("user_address")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->find();
		 if( !$info ) $this->error('数据不存在，请核对');
		 $info['areaTxt'] = "{$info['province_name']}-{$info['city_name']}-{$info['area_name']}";
		 return $this->renderSuccess(compact('info'));
	 }
	 
	 /**
	  * 设置默认收货地址
	  */
	 public function defaultaddress() {
		 $id = $this->request->param("id/d" , 0);
		 $info = db("user_address")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->find();
		 if( !$info ) $this->error('数据不存在，请核对');
		 db("user_address")->where(['user_id' => $this->user_info['user_id']])->update(['is_default' => 0]);
		 db("user_address")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->update(['is_default' => 1]);
		 $this->success('设置成功');
	 }
	 
	 /**
	  * 删除收货地址
	  */
	 public function deladdress() {
		 $id = $this->request->param("id/d" , 0);
		 $result = db("user_address")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->delete();
		 if( $result ) {
			 $this->success('删除成功');
		 } else {
			 $this->error('删除失败，请重试');
		 }
	 }
	
	/**
	 * 新增收藏
	 */
	public function addcollection() {
		$goodsid = $this->request->param("goodsid/d" , 0);
		if( !$goodsid ) $this->error('商品数据不能为空');
		if( !db("goods_collection")->where(['goods_id' => $goodsid , 'user_id' => $this->user_info['user_id']])->find() ) {
			db("goods_collection")->insert([
				'goods_id' => $goodsid,
				'user_id' => $this->user_info['user_id'],
				'goods_type' => db("goods")->where(['goods_id' => $goodsid])->value("goods_type"),
				'create_time' => time()
			]);
			$this->success('增加成功');
		} else {
			db("goods_collection")->where(['goods_id' => $goodsid,'user_id' => $this->user_info['user_id']])->delete();
			$this->success('收藏取消成功');
		}
	}
	
	/**
	 * 收藏列表
	 */
	public function collection() {
		$type = $this->request->param("type/d" , 1);
		$type = $type == 1 ? 1 : 2;
		$list = thumbImgUrl(db("goods_collection")->alias("gc")->join("yoshop_goods g",'g.goods_id = gc.goods_id')
				->where(['gc.user_id' => $this->user_info['user_id'],'is_delete' => 0 ,'gc.goods_type' => $type, 'goods_status' => 10])
				->field("gc.id,g.goods_name,g.thumb,g.goods_id,(select min(goods_price) from yoshop_goods_spec where goods_id = g.goods_id) as price,g.goods_type,g.goods_type_price,g.goods_integral")
				->order('gc.id DESC')->paginate(10, false, [
			'query' => Request::instance()->request()
		])->each(function($item , $key){
			if( $item['goods_type'] == 2 && $item['goods_type_price'] == 1 ) {
				$item['price'] = '￥' . $item['price'] . ' + 积分：' . $item['goods_integral'];
			} else if( $item['goods_type'] == 2 && $item['goods_type_price'] == 2 ) {
				$item['price'] = '积分：' . $item['goods_integral'];
			} else {
				$item['price'] = '￥' . $item['price'];
			}
			return $item;
		})->toArray()['data']);
		return $this->renderSuccess(compact('list'));
	}
	
	/**
	 * 删除收藏
	 */
	public function delecollection() {
		$collect_id = $this->request->param("goodsid/d" , 0);
		if( !$collect_id ) $this->error('数据异常');
		$res = db("goods_collection")->where(['user_id' => $this->user_info['user_id'],'goods_id' => $collect_id])->delete();
		if( $res ) {
			$this->success('删除成功');
		} else {
			$this->error('删除失败，请重试');
		}
	}
	
	/**
	 * 个人中心
	 */
	public function center() {
		$user = [
			'user_id' => $this->user_info['user_id'],
			'share_code' => $this->user_info['share_code'],
			'mobile' => $this->user_info['mobile'],
			'nickname' => $this->user_info['nickname'],
			'avatar' => $this->user_info['avatar'],
			'money' => $this->user_info['money'],
			'integral' => $this->user_info['integral'],
			'identity_name' => $this->user_info['identity_name'],
			'is_open_cart' => $this->user_info['is_open_cart'],
			'service_num' => $this->user_info['service_num'],
			'is_item' => $this->user_info['is_item'],
			'baoyang_num' => $this->user_info['baoyang_num'],
			'sales_achievement' => $this->user_info['sales_achievement'],
		];
		//车辆信息
		$cart_list = db("member_auto_info")->where(['user_id' => $this->user_info['user_id']])
					 ->field("id,auto_brand_name,auto_type_name,frame_number,travel_mileage")->select()->toArray();
		$user['cart_list'] = $cart_list;
		//查询会员中心广告
		$user['ads'] = thumbImgUrl(db("ads")->where(['type' => 'member_center_ads' , 'status' => 1])->field("title,target_type,target_data,thumb")->order(['sort' => 'DESC','ads_id' => 'DESC'])->find());
		//随机查询商品
		$goodsmodel = new GoodsModel;
		$user['goods'] = thumbImgUrl($goodsmodel->pageList(['goods_type' => 1] , 1)->toArray()['data']);
		$config = SettingModel::getItem('store');
		$user['open_circulation'] = $config['open_circulation'];
		$user['integral_log_open'] = $config['integral_log_open'];
		$user['my_firend_open'] = $config['my_firend_open'];
		$userModel = new UserModel;
		$total_price = $userModel->itemPrices( $this->user_info['user_id'] );
		$config_fx = SettingModel::getItem('distribution');
		$fx_item_price = ( isset( $config_fx['item']['condition'] ) ? $config_fx['item']['condition'] * 10000 : 0 );
		$user['is_sh_item'] = $this->user_info['is_item'] <= 0 && $fx_item_price > 0 && $total_price > $fx_item_price ? 1 : 0;
		return $this->renderSuccess(compact('user'));
	}
	
	/**
	 * 用户消费日志
	 */
	public function moneyLog() {
		
		$user = [
			'money' => $this->user_info['money'],
			'total_money' => $this->user_info['total_money'],
		];
		
		$list = db('user_money_log')->where(['user_id' => $this->user_info['user_id']])->order('id DESC')->paginate(10, false, [ 'query' => Request::instance()->request() ])->each(function($item , $key){
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
			unset( $item['user_id'] );
			return $item;
		})->toArray()['data'];
		return $this->renderSuccess(compact('user' , 'list'));
	}
	
	/**
	 * 用户积分消费日志
	 */
	public function integralLog() {
		
		$user = [
			'integral' => $this->user_info['integral'],
			'total_integral' => $this->user_info['total_integral'],
		];
		
		$list = db('user_integral_log')->where(['user_id' => $this->user_info['user_id']])->order("id DESC")->paginate(10, false, [ 'query' => Request::instance()->request() ])->each(function($item , $key){
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
			unset( $item['user_id'] );
			return $item;
		})->toArray()['data'];
		return $this->renderSuccess(compact('user' , 'list'));
	}
	
	/**
	 * 订单列表
	 */
	public function order() {
		$status = $this->request->param("status/d" , 0);
		$type = $this->request->param("type/d" , 1);
		$type = $type == 1 ? 1 : 2;
		$where = ['user_id' => $this->user_info['user_id'] , 'type' => $type];
		switch($status) {
			case 1 : //待付款
				$where['pay_status'] = 10;
				$where['order_status'] = 10;
			break;
			case 2 : //待发货
				$where['pay_status'] = 20;
				$where['delivery_status'] = 10;
			break;
			case 3 : //待收货
				$where['pay_status'] = 20;
				$where['delivery_status'] = 20;
				$where['receipt_status'] = 10;
			break;
			case 4 : //已完成
				$where['order_status'] = 30;
			break;
			case 5 : //退换货
				$where['order_status'] = 20;
			break;
		}
		
		$list = db("order")->where($where)->field("order_id,type,order_no,total_price,pay_price,is_comment,pay_integral,pay_status,delivery_status,receipt_status,order_status,create_time")->order("order_id DESC")->paginate(10, false, [ 'query' => Request::instance()->request() ])->each(function($item , $key){
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
			if( $item['pay_status'] == 10 && $item['order_status'] == 10 ) {
				$item['status'] = 1;
				$item['status_name'] = '待付款';
			} else if( $item['pay_status'] == 20 && $item['delivery_status'] == 10 ) {
				$item['status'] = 2;
				$item['status_name'] = '待发货';
			} else if( $item['pay_status'] == 20 && $item['delivery_status'] == 20 && $item['receipt_status'] == 10 ) {
				$item['status'] = 3;
				$item['status_name'] = '待收货';
			} else if( $item['order_status'] == 30 ) {
				$item['status'] = 4;
				$item['status_name'] = '交易完成';
			} else if( $item['order_status'] == 20 ) {
				$item['status'] = 5;
				$item['status_name'] = '失效';
			}
			if( $item['type'] == 1 ) {
				unset( $item['pay_price'] );
				$field="thumb,goods_name,goods_attr,goods_price,total_num";
			} else {
				unset( $item['pay_integral'] );
				unset( $item['pay_price'] );
				$field="thumb,goods_name,goods_attr,goods_price,total_num,goods_integral";
			}
			unset( $item['pay_status'] );
			unset( $item['delivery_status'] );
			unset( $item['receipt_status'] );
			unset( $item['order_status'] );
			//获取订单商品信息
			$item['goods'] = thumbImgUrl(db("order_goods")->where(['order_id' => $item['order_id']])
							 ->field($field)->select()->toArray());
			$item['goods_count'] = array_sum(array_column($item['goods'],'total_num'));
			return $item;
		})->toArray()['data'];
		return $this->renderSuccess(compact('list'));
	}
	
	/**
	 * 订单详情
	 */
	public function orderinfo() {
		$orderid = $this->request->param("orderid/d" , 0);
		$orderinfo = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $orderid])->find();
		if(!$orderinfo) $this->error('订单信息错误');
		if( $orderinfo['pay_status'] == 10 && $orderinfo['order_status'] == 10 ) {
			$orderinfo['status'] = 1;
			$orderinfo['status_name'] = '待付款';
		} else if( $orderinfo['pay_status'] == 20 && $orderinfo['delivery_status'] == 10 ) {
			$orderinfo['status'] = 2;
			$orderinfo['status_name'] = '待发货';
		} else if( $orderinfo['pay_status'] == 20 && $orderinfo['delivery_status'] == 20 && $orderinfo['receipt_status'] == 10 ) {
			$orderinfo['status'] = 3;
			$orderinfo['status_name'] = '待收货';
		} else if( $orderinfo['order_status'] == 30 ) {
			$orderinfo['status'] = 4;
			$orderinfo['status_name'] = '交易完成';
		} else if( $orderinfo['order_status'] == 20 ) {
			$orderinfo['status'] = 5;
			$orderinfo['status_name'] = '失效';
		}
		unset( $orderinfo['pay_status'] );
		unset( $orderinfo['delivery_status'] );
		unset( $orderinfo['receipt_status'] );
		unset( $orderinfo['order_status'] );
		unset( $orderinfo['user_id'] );
		unset( $orderinfo['update_time'] );
		$orderinfo['create_time'] = date("Y-m-d H:i:s" , $orderinfo['create_time']);
		if( $orderinfo['type'] == 1 ) {
			$field="thumb,goods_name,goods_attr,goods_price,total_num";
		} else {
			$field="thumb,goods_name,goods_attr,goods_price,total_num,goods_integral";
		}
		//获取订单商品信息
		$orderinfo['goods'] = thumbImgUrl(db("order_goods")->where(['order_id' => $orderinfo['order_id']])
							  ->field($field)->select()->toArray());
		//获得用户收货信息
		$orderinfo['address'] = db("order_address")->field("name,phone,detail as address,province_id,city_id,region_id")->where(['order_id' => $orderinfo['order_id'] , 'user_id' => $this->user_info['user_id']])->find();
		$province_name = db("region")->where(['id' => $orderinfo['address']['province_id']])->value("name");
		$city_name = db("region")->where(['id' => $orderinfo['address']['city_id']])->value("name");
		$area_name = db("region")->where(['id' => $orderinfo['address']['region_id']])->value("name");
		$orderinfo['address']['address'] = $province_name.$city_name.$area_name . $orderinfo['address']['address'];
		$orderinfo['pay_time'] = date("Y-m-d H:i:s" , $orderinfo['pay_time']);
		$orderinfo['pay_type'] = $orderinfo['pay_type'] == 1 ? '微信支付' : ( $orderinfo['pay_type'] == 2 ? '支付宝支付' : '余额支付' );
		unset( $orderinfo['address']['province_id'] );
		unset( $orderinfo['address']['city_id'] );
		unset( $orderinfo['address']['region_id'] );
		return $this->renderSuccess(compact('orderinfo'));
	}
	
	/**
	 * 订单取消
	 */
	public function ordercancel(){
		$orderid = $this->request->param("orderid/d" , 0);
		$orderinfo = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $orderid])->find();
		if(!$orderinfo) $this->error('订单信息错误');
		$result = db("order")->where(['order_id' => $orderid])->update(['order_status' => 20]);
		if( $result ) {
			$this->success("订单取消成功");
		} else {
			$this->error("操作失败");
		}
	}
	
	/**
	 * 确定收货
	 */
	public function orderreceived(){
		$orderid = $this->request->param("orderid/d" , 0);
		$orderinfo = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $orderid])->find();
		if(!$orderinfo) $this->error('订单信息错误');
		$result = db("order")->where(['order_id' => $orderid])->update(['order_status' => 30 , 'receipt_status' => 20 , 'receipt_time' => time()]);
		if( $result ) {
			$this->success("订单收货成功");
		} else {
			$this->error("操作失败");
		}
	}
	
	/**
	 * 订单删除
	 */
	public function orderdelete() {
		$orderid = $this->request->param("orderid/d" , 0);
		$orderinfo = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $orderid])->find();
		if(!$orderinfo) $this->error('订单信息错误');
		$result = db("order")->where(['order_id' => $orderid])->delete();
		if( $result ) {
			//删除商品数据
			db("order_goods")->where(['order_id' => $orderid])->delete();
			//删除收货数据
			db("order_address")->where(['order_id' => $orderid])->delete();
			$this->success("订单删除成功");
		} else {
			$this->error("操作失败");
		}
	}
	
	/**
	 * 提醒发货
	 */
	public function orderremind() {
		$orderid = $this->request->param("orderid/d" , 0);
		$orderinfo = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $orderid])->find();
		if(!$orderinfo) $this->error('订单信息错误');
		if( $orderinfo['remind_time'] > strtotime(date("Y-m-d")) && $orderinfo['remind_time'] < strtotime(date("Y-m-d")) + 24 * 3600 -1 ) {
			$this->error("一天只能提醒一次，请勿重复提醒");
		}
		$result = db("order")->where(['order_id' => $orderid])->update(['remind_time' => time()]);
		if( $result ) {
			$this->success("提醒发货成功");
		} else {
			$this->error("操作失败");
		}
	}
	
	/**
	 * 订单物流信息查看
	 */
	public function expresslist() {
		$orderid = $this->request->param("orderid/d" , 0);
		$orderinfo = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $orderid])->find();
		if(!$orderinfo) $this->error('订单信息错误');
		if( $orderinfo['express_company'] && $orderinfo['express_no'] ) {
			$express_list = config("express_name_list");
			$express_code = '';
			foreach( $express_list as $k => $v ) {
				if( $v == $orderinfo['express_company'] ) $express_code = $k;
			}
			$info['express_name'] = $orderinfo['express_company'];
			$info['express_no'] = $orderinfo['express_no'];
			try{
				$info['express_list'] = [];
				//获得快递信息
				/*$curl = curl_init();
				curl_setopt($curl, CURLOPT_URL, "http://www.kuaidi100.com/query?type=".$express_code."&postid=" . $info['express_no']);
				curl_setopt($curl, CURLOPT_HEADER, 0);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
				curl_setopt($curl,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
				$result = curl_exec($curl);
				curl_close($curl);
				$result = json_decode( $result , true);
				*/
				$result = getExpress($info['express_no']);
				if( $result && $result['code'] == 'OK' ) {
					$express_list = [];
					if( $result['list'] ) {
						foreach( $result['list'] as $k1 => $v1 ) {
							$express_list[] = ['context' => $v1['content'] , 'time' => $v1['time']];
						}
					}
					$info['express_list'] = $express_list;
				}
				$this->success("success" , $info);
			} catch (Exception $e) {
				$this->error("快递数据获取异常，请联系平台");
			}
		}
	}
	
	/**
	 * 用户评论
	 */
	public function ordercomment() {
		$orderid = $this->request->param("orderid/d" , 0);
		$orderinfo = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $orderid])->find();
		if(!$orderinfo) $this->error('订单信息错误');
		if( request()->isPost() ) {
			$data = $this->request->param("data" , '');
			if( !$data ) $this->error('数据有误');
			$data = json_decode( htmlspecialchars_decode($data) , true );
			if( !$data ) $this->error('数据有误');
			foreach( $data as $k => $v ) {
				$types = 1;
				if($v['type'] <= 5 && $v['type'] >= 4 ) {
					$types = 3;
				} else if( $v['type'] <= 3 && $v['type'] >= 2 ) {
					$types = 2;
				}
				db("goods_comment")->insert([
					'user_id' => $this->user_info['user_id'],
					'goods_id' => $v['goods_id'],
					'star' => $v['star'],
					'type' => $types,
					'content' => $v['content'],
					'thumb_list' => $v['thumb'] ? json_encode( explode(',' , $v['thumb'] ) ) : '',
					'create_time' => time()
				]);
			}
			
			//修改订单
			db("order")->where(['order_id' => $orderid])->update(["is_comment" => 1]);
			$this->success("订单评论成功");
		} else {
			if( $orderinfo['type'] == 1 ) {
				$field="thumb,goods_name,goods_attr,goods_price,total_num,goods_id";
			} else {
				$field="thumb,goods_name,goods_attr,goods_price,total_num,goods_integral,goods_id";
			}
			$goods_list = thumbImgUrl(db("order_goods")->where(['order_id' => $orderinfo['order_id']])
						  ->field($field)->select()->toArray());
			return $this->renderSuccess(compact('goods_list'));
		}
	}
	
	/**
	 * 服务中心
	 */
	public function servicecenter() {
		$lng = $this->request->param("lng" , 0);
		$lat = $this->request->param("lat" , 0);
		$type = $this->request->param("type/d" , 1);
		$size = 10;
		$page = $this->request->param('page/d' , 1);
		$field = '';
		if( $lng && $lat ) {
			$field = ',(POWER(MOD(ABS(lng - '.$lng.'),360),2) + POWER(ABS(lat - '.$lat.'),2)) AS distance';
			$order = 'distance';
		} else {
			$order = 'shop_id DESC';
		}
		$sql = 'SELECT shop_id,shop_name,province_name,city_name,area_name,address,tel,lng,lat'.$field.' FROM `yoshop_shop` WHERE status = 1 AND `type` LIKE "%,'.htmlspecialchars($type).',%" ORDER BY ' . $order . ' LIMIT ' . ( ( $page  - 1 ) * $size ) . ',' . $size;
		$list = Db::query( $sql );
		foreach( $list as $k => &$v ) {
			$v['address'] = $v['province_name'].$v['city_name'].$v['area_name'].$v['address'];
			$v['num'] = 0;
			if( $lng && $lat ) {
				$distance = getDistance($lng,$lat,$v['lng'],$v['lat'],1,0);
				if( $distance > 1000 ) {
					$distance = round( $distance / 1000 , 1 ) . "KM";
				} else {
					$distance = $distance . "M";
				}
				$v['num'] = $distance;
			}
			unset( $list[$k]['province_name'], $list[$k]['city_name'], $list[$k]['area_name'] );
		}
		return $this->renderSuccess(compact('list'));
	}
	
	
	/**
	 * 预约
	 */
	public function cartreserve() {
		if( !$this->user_info['is_open_cart'] ) {
			exit(json_encode(array('code' => 416 , 'msg' => '您还未开通会员卡，请前往开通！')));
		}
		$shop_id = $this->request->param("id/d" , 0);
		$cart_id = $this->request->param("cart_id/d" , 0);
		$shopinfo = thumbImgUrl( db("shop")->field('shop_id,logo,user_id,shop_name,province_name,city_name,area_name,address,tel')->where(['shop_id' => $shop_id , 'status' => 1])->find() );
		if(!$shopinfo) $this->error('4s店不存在');
		if( request()->isPost() ) {
			if( $this->user_info['service_num'] <= 0 &&  $type == 1 ) {
				exit(json_encode(array('code' => 416 , 'msg' => '免费换油机会已用完，请充值会员卡获得换取机油的机会')));
			}
			$cart_id = $this->request->param('cart_id/d' , 0);
			$cart_id <= 0 ? $this->error('请选择您的服务车辆') : '';
			$type = $this->request->param('type/d' , 0);
			$type <= 0 ? $this->error('请选择服务类型') : '';
			$contact = $this->request->param('contact/s' , '');
			!$contact ? $this->error('联系人不能为空') : '';
			$mobile = $this->request->param('mobile/s' , '');
			!$mobile ? $this->error('联系手机号不能为空') : '';
			$mileage = $this->request->param('mileage');
			$yuyue_time = $this->request->param('yuyue_time/s' , '');
			!$yuyue_time ? $this->error('预约时间不能为空') : '';
			$specific_time = $this->request->param('specific_time/s','');
			!$specific_time ? $this->error('预约详细时间不能为空') : '';
			//查询车辆是否存在
			$cart_info = db("member_auto_info")->where(['user_id' => $this->user_info['user_id'] , 'id' => $cart_id])->field("auto_brand_name,displacement,auto_type_name")->find();
			if( !$cart_info ) $this->error('车辆不存在');
			$result = db("shop_yuyue_service")->insert([
				'shop_id' => $shop_id,
				'user_id' => $this->user_info['user_id'],
				'auto_info_id' => $cart_id,
				'type' => $type == 1 ? 1 : 2,
				'contact' => $contact,
				'mobile' => $mobile,
				'mileage' => $mileage,
				'yuyue_time' => $yuyue_time,
				'specific_time' => $specific_time,
				'cart_brand' => $cart_info['auto_brand_name'] . $cart_info['auto_type_name'],
				'displacement' => $cart_info['displacement'],
				'create_time' => time()
			]);
			if( $result ) {
				$msg = '有新的用户预约了【'.$yuyue_time . ' / ' .$specific_time. '】的' . ( $type == 1 ? '换油' : '补油' ) . '服务，请在商家预约中心进行确认。';
				$this->getui->sendToClient($shopinfo['user_id'] , '您有新的预约消息需要确认',$msg);
				if( $type == 1 ) {
					db("user")->where(['user_id' => $this->user_info['user_id']])->update(['service_num' => $this->user_info['service_num'] - 1]);
				}
				$this->success('预约成功');
			} else {
				$this->errur('预约失败');
			}
		} else {
			$shopinfo['address'] = $shopinfo['province_name'].$shopinfo['city_name'].$shopinfo['area_name'].$shopinfo['address'];
			unset( $shopinfo['province_name'], $shopinfo['city_name'], $shopinfo['area_name'] );
			//获取最新的车辆信息
			$where = ['user_id' => $this->user_info['user_id']];
			if( $cart_id > 0 ) {
				$where['id'] = $cart_id;
			}
			$shopinfo['cart'] = db("member_auto_info")->where( $where )->field("id,auto_brand_name,auto_type_name,frame_number,travel_mileage,carowner,carowner_mobile")->order("id DESC")->find();
			return $this->renderSuccess(compact('shopinfo'));
		}
	}
	
	
	/**
	 * 车辆信息列表
	 */
	public function autolist(){
		$list = db('member_auto_info')->where(['user_id' => $this->user_info['user_id']])->field("id,auto_brand_name,auto_type_name,frame_number,travel_mileage")
					->paginate(10, false, [ 'query' => Request::instance()->request() ])->toArray()['data'];
		return $this->renderSuccess(compact('list'));
	}
	
	/**
	 * 驾驶证图片认证
	 */
	public function cartcheck() {
		set_time_limit(0);
		$file = request()->file('files');  
        if(empty($file)) {  
            $this->error('请选择上传文件');  
        }  
        $info = $file->move(WEB_PATH.DS.'uploads'); 
        $filename = $info->getSaveName();
        if($filename){
			$result = carCartIdCheck( WEB_PATH.'uploads/' . $filename );
			if( $result === false ) {
				$this->error("识别失败，请重试");
			}
			if( trim($result['plate_num']) == '' || trim($result['vin']) == '' || trim($result['owner']) == '' ) {
				$this->error("识别失败，请保持证件的平整，不要有反光。");
			}
			$result = array_merge(['file_path' => thumbImgUrl('/uploads/'.$filename) , 'path' => '/uploads/'.$filename] , $result);
            $this->success('识别成功' , $result);  
        }else{
            $this->error($file->getError());  
        }
	}
	
	/**
	 * 修改车辆信息
	 */
	public function editvehicle() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据异常");
		$info = db("member_auto_info")->where(['id' => $id , 'user_id' => $this->user_info['user_id']])->find();
		$info['path'] =  $info['driving_license'];
		$info['driving_license'] =  thumbImgUrl( $info['driving_license'] );
		if( !$info ) {
			$this->error("数据不存在");
		}
		$info['create_time'] = date("Y-m-d H:i:s" , $info['create_time']);
		if( request()->isPost() ) {
			$carowner = $this->request->param('carowner','');
			$carowner?$carowner:$this->error('车主不能为空');
			
			$carowner_mobile = $this->request->param('carowner_mobile','');
			$carowner_mobile?$carowner_mobile:$this->error('车主联系电话不能为空');
			
			$travel_mileage = $this->request->param('travel_mileage','');
			$travel_mileage?$travel_mileage:$this->error('行驶公里数不能为空');
			
			$result = db("member_auto_info")->where(['id' => $id])->update([
				'carowner' => $carowner,
				'carowner_mobile' => $carowner_mobile,
				'travel_mileage' => $travel_mileage,
			]);
			if( $result ) {
				$this->success("车辆信息修改成功");
			} else {
				$this->error("修改失败");
			}
		}else {
			unset($info['user_id']);
			return $this->renderSuccess(compact('info'));
		}
	}
	
	/**
	 * 车辆添加
	 */
	public function addvehicle() {
		$type = $this->request->param('type','');
		$type?$type:$this->error('车辆类型不能为空');
		
		$plate_num = $this->request->param('plate_num','');
		$plate_num?$plate_num:$this->error('车牌号不能为空');
		
		$auto_brand_id = $this->request->param('auto_brand_id','');
		$auto_brand_id?$auto_brand_id:$this->error('请选择品牌');
		
		$auto_type_id = $this->request->param('auto_type_id','');
		$auto_type_id?$auto_type_id:$this->error('请选择型号');
		
		$driving_license = $this->request->param('driving_license','');
		$driving_license?$driving_license:$this->error('请上传驾驶证');
		
		$carowner = $this->request->param('carowner','');
		$carowner?$carowner:$this->error('车主不能为空');
		
		$carowner_mobile = $this->request->param('carowner_mobile','');
		$carowner_mobile?$carowner_mobile:$this->error('车主联系电话不能为空');
		
		$displacement = $this->request->param('displacement/s',0);
		$displacement?$displacement:$this->error('车辆排量不能为空');
		
		$travel_mileage = $this->request->param('travel_mileage','');
		$travel_mileage?$travel_mileage:$this->error('行驶公里数不能为空');
		
		$frame_number = $this->request->param('frame_number','');
		$frame_number?$frame_number:$this->error('车架号不能为空');
		
		$result = db("member_auto_info")->insert([
			'user_id' => $this->user_info['user_id'],
			'type' => $type,
			'plate_num' => $plate_num,
			'auto_brand_id' => $auto_brand_id,
			'auto_brand_name' => db("auto_brand")->where(['id' => $auto_brand_id])->value("title"),
			'auto_type_id' => $auto_type_id,
			'auto_type_name' => db("auto_type")->where(['id' => $auto_type_id])->value("title"),
			'driving_license' => $driving_license,
			'carowner' => $carowner,
			'carowner_mobile' => $carowner_mobile,
			'travel_mileage' => $travel_mileage,
			'frame_number' => $frame_number,
			'displacement' => $displacement,
			'create_time' => time()
		]);
		
		if( $result ) {
			$this->success("车辆添加成功");
		} else {
			$this->error("添加失败，请重试");
		}
	}
	
	
	/**
	 * 车辆信息删除
	 */
	public function delvehicle() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据异常");
		$info = db("member_auto_info")->where(['id' => $id , 'user_id' => $this->user_info['user_id']])->find();
		if( !$info ) {
			$this->error("数据不存在");
		}
		$result = db("member_auto_info")->where(['id' => $id])->delete();
		if( $result ) {
			$this->success("车辆删除成功");
		} else {
			$this->error("删除失败");
		}
	}
	
	/**
	 * 车辆详情
	 */
	public function infovehicle() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据异常");
		$info = thumbImgUrl( db("member_auto_info")->where(['id' => $id , 'user_id' => $this->user_info['user_id']])->find() );
		if( !$info ) {
			$this->error("数据不存在");
		}
		$info['create_time'] = date("Y-m-d H:i:s" , $info['create_time']);
		unset( $info['user_id'] );
		$this->success("success", $info);
	}
	
	/**
	 * 预约中心列表
	 */
	public function yuyuelist() {
		$type = $this->request->param("type/d" , 0);
		$where = ['ys.user_id' => $this->user_info['user_id'],'ys.user_delete' => 1];
		$status_field = [ 1 => 0 , 2 => 1 , 3 => 2 , 4 => 3 , 5 => "4,5"];
		if( isset( $status_field[$type] ) ) {
			$where['ys.status'] = ['IN' , $status_field[$type]];
		}
		$list = thumbImgUrl(db("shop_yuyue_service")->alias("ys")->join("yoshop_shop s",'s.shop_id = ys.shop_id')->where($where)->order("id DESC")
				->field("ys.id,s.shop_name,s.logo,ys.cart_brand,ys.type,ys.contact,ys.mobile,s.province_name,s.city_name,s.area_name,s.address,ys.yuyue_time,ys.specific_time,ys.status,ys.is_comment,ys.create_time")
				->paginate(10, false, [ 'query' => Request::instance()->request() ])->each(function($item ,$key){
					$item['create_time'] = date("Y-m-d H:i" , $item['create_time']);
					$item['address'] = $item['province_name'].$item['city_name'].$item['area_name'].$item['address'];
					unset( $item['province_name'], $item['city_name'], $item['area_name'] );
					$fields = [ 0 => '待确认' , 1 => '预约中' , 2 => '服务中' , 3 => '已完成' , 4 => '待确认取消' , 5 => '已确认取消' , 6 => '已拒绝'];
					$item['status_name'] = $fields[$item['status']];
					return $item;
				})->toArray()['data']);
		return $this->renderSuccess(compact('list'));
	}
	
	/**
	 * 预约详情
	 */
	public function yuyueinfo() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据错误");
		$info = thumbImgUrl(db("shop_yuyue_service")->alias("ys")->join("yoshop_shop s",'s.shop_id = ys.shop_id')->where(['ys.user_id' => $this->user_info['user_id'] ,'ys.user_delete' => 1 , 'ys.id' => $id])
				->field("ys.*,s.shop_name,s.logo,s.province_name,s.city_name,s.area_name,s.address,s.tel")->find());
		if( !$info ) $this->error("数据不存在！");
		$info['create_time'] = date("Y-m-d H:i" , $info['create_time']);
		$info['address'] = $info['province_name'].$info['city_name'].$info['area_name'].$info['address'];
		//获得预约车辆的数据
		$auto_info = db("member_auto_info")->where(['id' => $info['auto_info_id']])->field("maintain_total,replaceoil_total,last_yuyue_time")->find();
		$info = array_merge( $info , $auto_info );
		unset( $info['province_name'], $info['city_name'], $info['area_name'], $info['user_id'], $info['shop_id'],$info['auto_info_id'] );
		//获得二维码数据
		$info['qrcode_url'] = '';
		if( $info['status'] == 1 ) {
			include( APP_PATH . 'common/library/phpqrcode/phpqrcode.php' );
			$qrcode_file = WEB_PATH . 'uploads/qrcode/';
			if( !file_exists($qrcode_file) ) mkdir( $qrcode_file , 0777 , true );
			\QRcode::png('hexiao_' . $id, $qrcode_file . 'yuyue_'.$id.'.png', "L", 18, 2); 
			$info['qrcode_url'] = thumbImgUrl( '/uploads/qrcode/' . 'yuyue_'.$id.'.png' );
		}
		$fields = [ 0 => '待确认' , 1 => '预约中' , 2 => '服务中' , 3 => '已完成' , 4 => '待确认取消' , 5 => '已确认取消' , 6 => '已拒绝'];
		$info['status_name'] = $fields[$info['status']];
		return $this->renderSuccess(compact('info'));
	}
	
	/**
	 * 预约评论
	 */
	public function yuyuecomment() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据错误");
		$info = thumbImgUrl(db("shop_yuyue_service")->alias("ys")->join("yoshop_shop s",'s.shop_id = ys.shop_id')->where(['ys.user_id' => $this->user_info['user_id'] , 'ys.is_comment' => 0 ,'ys.user_delete' => 1 , 'ys.id' => $id])
				->field("ys.id,ys.shop_id,ys.user_id AS shop_user_id,ys.contact,ys.cart_brand,s.shop_name,s.logo,s.province_name,s.city_name,s.area_name,s.address,s.tel")->find());
		if(!$info) $this->error('预约数据不存在');
		$info['address'] = $info['province_name'].$info['city_name'].$info['area_name'].$info['address'];
		unset( $info['province_name'], $info['city_name'], $info['area_name'] );
		if( request()->isPost() ) {
			$type = $this->request->param("type/d" , 1);
			$service_star = $this->request->param("service_star/d" , 1);
			$skill_star = $this->request->param("skill_star/d" , 1);
			$content = $this->request->param("content" , '');
			if( !$content ) $this->error('评论内容不能为空');
			db("shop_yuyue_service_comment")->insert([
				'user_id' => $this->user_info['user_id'],
				'shop_id' => $info['shop_id'],
				'yuyue_service_id' => $id,
				'service_star' => $service_star,
				'skill_star' => $skill_star,
				'type' => $type,
				'content' => htmlspecialchars( $content ),
				'create_time' => time()
			]);
			$this->getui->sendToClient($info['shop_user_id'] , '您有一条新的服务评论' , '服务用户【'.$info['contact'].'】，服务车型【'.$info['cart_brand'].'】，对您进行了的服务做出了评论，请在服务评论中心查看。' );
			//修改预约信息
			db("shop_yuyue_service")->where(['id' => $id])->update(["is_comment" => 1]);
			$this->success("预约评论成功");
		} else {
			return $this->renderSuccess(compact('info'));
		}
	}
	
	/**
	 * 预约确认完成
	 */
	public function yuyuecomplete() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据错误");
		$info = db("shop_yuyue_service")->where(['user_id' => $this->user_info['user_id'] ,'user_delete' => 1 , 'id' => $id])->find();
		if(!$info) $this->error('预约数据不存在');
		$result = db("shop_yuyue_service")->where(['id' => $id])->update(['is_settlement' => ( $info['type'] == 1 ? 1 : 0 ) , 'status' => 3, 'user_complete_time' => time()]);
		if( $result ) {
			$shop_info = db("shop")->where(['shop_id' => $info['shop_id']])->find();
			if( $shop_info ) {
				$this->getui->sendToClient($shop_info['user_id'] , '有新的用户确认服务完成' , '您服务的用户【'.$info['contact'].'】，服务车型【'.$info['cart_brand'].'】，确认完成了此次服务，请在商家中心查看。');
			}
			//公里数和预约时间写入车辆信息
			$auto_field = $info['type'] == 1 ? 'maintain_total' : 'replaceoil_total';
			$auto_info = db("member_auto_info")->where(['id' => $info['auto_info_id']])->find();
			if( $auto_info ) {
				$auto_save_data = [
					'last_yuyue_time' => date("Y-m-d"),
					'travel_mileage' => $info['mileage'],
					$auto_field => $auto_info[$auto_field] + 1
				];
				db("member_auto_info")->where(['id' => $info['auto_info_id']])->update($auto_save_data);
			}
			$this->success("预约确认成功");
		} else {
			$this->error("操作失败");
		}
	}
	
	/**
	 * 预约删除
	 */
	public function yuyuedel() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据错误");
		$info = db("shop_yuyue_service")->where(['user_id' => $this->user_info['user_id'] ,'user_delete' => 1 , 'id' => $id])->find();
		if(!$info) $this->error('预约数据不存在');
		if( !in_array( $info['status'] , array(3,5,6) )) $this->error("订单不能删除");
		$result = db("shop_yuyue_service")->where(['id' => $id])->update(['user_delete' => 0]);
		if( $result ) {
			$this->success("预约删除成功");
		} else {
			$this->error("操作失败");
		}
	}
	
	/**
	 * 预约取消
	 */
	public function yuyuecancel() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据错误");
		$info = db("shop_yuyue_service")->where(['user_id' => $this->user_info['user_id'] ,'user_delete' => 1 , 'id' => $id])->find();
		if(!$info) $this->error('预约数据不存在');
		if( !in_array( $info['status'] , array(0,1) )) $this->error("订单不能取消");
		if( $info['status'] == 0 ) {
			$result = db("shop_yuyue_service")->where(['id' => $id])->update(['status' => 5]);
			if( $result ) {
				$member_info = db("user")->where(['user_id' => $info['user_id']])->find();
				if( $info['type'] == 1 && $member_info) {
					db("user")->where(['user_id' => $info['user_id']])->update(['service_num' => $member_info['service_num'] + 1]);
				}
				$this->success("预约直接取消成功");
			} else {
				$this->error("操作失败");
			}
		} else {
			$result = db("shop_yuyue_service")->where(['id' => $id])->update(['status' => 4]);
			if( $result ) {
				$shop_info = db("shop")->where(['shop_id' => $info['shop_id']])->find();
				if( $shop_info ) {
					$this->getui->sendToClient($shop_info['user_id'] , '您的新的预约服务取消申请' , '您确认的用户【'.$info['contact'].'】，服务车型【'.$info['cart_brand'].'】，申请了预约取消申请，请在商家中心查看。');
				}
				$this->success("申请预约取消成功，等待预约4s审核");
			} else {
				$this->error("操作失败");
			}
		}
	}
	
	/**
	 * 二级支付密码设置
	 */
	public function paypassset() {
		$pass = $this->request->param("pass" , '');
		if( $pass == '' ) $this->error("请输入您设置的支付密码");
		$code = $this->request->param("code/d" , 0);
		if( $code <= 0 ) $this->error("请输入您的短信认证码");
		//验证短信
        if( Cache::get($this->user_info['mobile'] . '_mobile_checked_3') != $code ) {
            $this->error('验证码错误，请核对');
        }
        //删除缓存
        Cache::rm($this->user_info['mobile'] . '_mobile_checked_3');
		$userModel = new UserModel;
		$result = db("user")->where(['user_id' => $this->user_info['user_id']])->update([
			'pay_pass' => $userModel->passmd5($pass)
		]);
		if( $result ) {
			$this->success("支付密码设置成功");
		} else {
			$this->error("设置失败");
		}
	}
	
	/**
	 * 设置
	 */
	public function setting() {
		$user_info = thumbImgUrl([
			'avatar' => $this->user_info['avatar'],
			'nickname' => $this->user_info['nickname'],
			'province' => $this->user_info['province'],
			'city' => $this->user_info['city'],
			'area' => $this->user_info['area'],
			'province_name' => $this->user_info['province_name'],
			'city_name' => $this->user_info['city_name'],
			'area_name' => $this->user_info['area_name'],
			'mobile' => $this->user_info['mobile'],
			'create_time' => date( "Y-m-d H:i:s" , $this->user_info['create_time'])
		]);
		
		$data = SettingModel::getItem('store');
		$user_info['tel'] = $data['tel'];
		return $this->renderSuccess(compact('user_info'));
	}
	
	/**
	 * 用户资料修改
	 */
	public function savesetting() {
		$field_key = ['nickname' => 'nickname' , 'sex' => 'sex' , 'avatar' => 'avatar'];
		$field = $this->request->param("field" , '');
		if( !$field || !isset( $field_key[$field] ) ) $this->error('数据异常');
		$value = $this->request->param("value", '');
		if( !$value ) $this->error('数据异常');
		$result = db("user")->where(['user_id' => $this->user_info['user_id']])->update([$field_key[$field] => $value]);
		if( $result ) {
			$this->success("更新成功");
		} else {
			$this->error("更新失败");
		}
	}
	
	/**
	 * 用户更新手机号
	 */
	public function savemobile() {
		$mobile = $this->request->param("mobile" , '');
		if( $mobile == '' ) $this->error("请输入您需要修改的新手机号");
		$code = $this->request->param("code/d" , 0);
		if( $code <= 0 ) $this->error("请输入您的短信认证码");
		 //验证短信
        if( Cache::get($mobile . '_mobile_checked_4') != $code ) {
            $this->error('验证码错误，请核对');
        }
		if( $this->user_info['mobile'] == $mobile ) $this->error('请输入新的手机号');
        if( db('user')->where(['mobile' => htmlspecialchars( $mobile )])->find() ) {
			$this->error("手机号已存在，请更换");
		}
		//删除缓存
        Cache::rm($mobile . '_mobile_checked_4');
		$result = db("user")->where(['user_id' => $this->user_info['user_id']])->update(['mobile' => $mobile]);
		if( $result ) {
			$this->success("更新成功");
		} else {
			$this->error("更新失败");
		}
	}
	
	/**
	 * 密码修改
	 */
	public function savepass() {
		$pass = $this->request->param("pass" , '');
		if( $pass == '' ) $this->error("原始不能为空");
		$new_pass = $this->request->param("new_pass" , '');
		if( $new_pass == '' ) $this->error("新密码不能为空");
		$userModel = new UserModel;
		if( $this->user_info['password'] != $userModel->passmd5($pass) ) {
			$this->error("原始密码不匹配");
		}
		$result = db("user")->where(['user_id' => $this->user_info['user_id']])->update(['password' => $userModel->passmd5($new_pass) , 'login_token' => '']);
		if( $result ) {
			$this->success("密码修改成功，请重新登录");
		} else {
			$this->error("密码修改失败");
		}
	}
	
	/**
	 * 我的好友
	 */
	public function myfriend() {
		//return $this->renderSuccess(compact('list'));
	}
	
	/**
	 * 会员卡订单下单
	 */
	public function membercartorder() {
		$data = SettingModel::getItem('distribution');
		if( isset( $data['order_price'] ) && $data['order_price'] > 0 ) {
			/*if( $info = db("member_cart_order")->where(['user_id' => $this->user_info['user_id'],'status' => 0])->find() ){
				$result = true;
				if( $info['price'] != $data['order_price'] || $data['order_consumption_num'] != $info['service_num'] ) {
					$result = db("member_cart_order")->where(['id' => $info['id']])->update(['service_num' => $data['order_consumption_num'],'price' => $data['order_price']]);
					$info['price'] = $data['order_price'];
				}
			} else {*/
				$info = [
					'ordersn' => date("YmdHis") . rand(1000 , 9999),
					'user_id' => $this->user_info['user_id'],
					'price' => $data['order_price'],
					'service_num' => $data['order_consumption_num'],
					'create_time' => time()
				];
				$result = db("member_cart_order")->insert( $info );
			//}
			if( $result ) {
				$pay = new PayModel;
				$order_info['ordersn'] = $info['ordersn'];
				$order_info['price'] = $info['price'];
				$order_data = ['total_price' => $info['price'] , 'order_no' => $info['ordersn']];
				$order_info['pay']['wx'] = $pay->payment( $order_data , 2 , 2);
				$order_info['pay']['ali'] = $pay->payment( $order_data , 1 , 2);
				$order_info['pay']['local'] = $this->user_info['money'];
				$this->success('下单成功' , $order_info);
			} else {
				$this->error('下单失败，请重试');
			}
		} else {
			$this->error("请联系管理员，错误码：30001");
		}
	}
	
	/**
	 * 系统消息列表
	 */
	public function sysmessage() {
		$usermodel = new UserModel;
		$list = db('system_message')->where(['user_id' => $this->user_info['user_id']])->order("id DESC")
				->paginate(10, false, [ 'query' => Request::instance()->request() ])->each(function($item , $key){
					$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
					return $item;	
				})->toArray()['data'];
		return $this->renderSuccess(compact('list'));
	}
	
	/**
	 * 系统消息删除
	 */
	public function delsysmessage() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据错误");
		$info = db("system_message")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->find();
		if(!$info) $this->error('系统消息不存在');
		$result = db("system_message")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->delete();
		if( $result ) {
			$this->success("系统消息删除成功");
		} else {
			$this->error("删除失败，请重试");
		}
	}
	
	/**
	 * 收益列表查看
	 */
	public function profitlist() {
		$type = $this->request->param("type/d" , 0);
		$where = ['user_id' => $this->user_info['user_id']];
		if( $type > 0 ) {
			$where['status'] = $type;
		}
		$list = db('member_cart_order_distribution')->where($where)
				->paginate(10, false, [ 'query' => Request::instance()->request() ])->each(function($item , $key){
					$item['create_time'] = date("Y-m-d H:i" , $item['create_time']);
					return $item;	
				})->toArray()['data'];
		$total_price = db('member_cart_order_distribution')->where($where)->sum("price");
		return $this->renderSuccess(compact('list' , 'total_price'));
	}
	
	/**
	 * 收益信息删除
	 */
	public function delprofit() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("数据错误");
		$info = db("member_cart_order_distribution")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->find();
		if(!$info) $this->error('消息不存在');
		//if( $info['status'] != 2 ) $this->error("信息不能删除");
		$result = db("member_cart_order_distribution")->where(['user_id' => $this->user_info['user_id'] , 'id' => $id])->delete();
		if( $result ) {
			$this->success("信息删除成功");
		} else {
			$this->error("删除失败，请重试");
		}
	}
	
	/**
	 * 提现审核
	 */
	public function withdrawcash() {
		$config = SettingModel::getItem('store');
		if( $config['tx_open_cart'] == 1 && $this->user_info['tx_total_price'] >= $config['tx_buy_price'] ) {
			exit(json_encode(array('code' => 416 , 'msg' => '非常抱歉，您提现累计积分已达到【'.$config['tx_buy_price'].'】分，您必须购买会员卡才能继续提现')));
		}
		if( request()->isPost() ) {
			if( $this->user_info['is_open_cart'] != 1 ) {
				exit(json_encode(array('code' => 416 , 'msg' => '非常抱歉，您未开通会员卡暂不能提现，请去开通会员卡！')));
			}
			$type = $this->request->param("type/s" , '');
			$type == '' ? $this->error("提现方式不能为空") : '';
			$datas = [];
			if( $type == '银行卡' ) {
				$datas['blank_type'] = $this->request->param("blank_type/s" , '');
				$datas['blank_type'] == '' ? $this->error("请选择要提现的银行") : '';
				
				$datas['name'] = $this->request->param("name/s" , '');
				$datas['name'] == '' ? $this->error("请输入开户人姓名") : '';
				
				$datas['blank_name'] = $this->request->param("blank_name/s" , '');
				$datas['blank_name'] == '' ? $this->error("请输入开户银行全称") : '';
				
				
			}
			
			$cart_no = $this->request->param("cart_no/s" , '');
			$cart_no == '' ? $this->error("请输入账号/卡号") : '';
			
			$account_img = $this->request->param("account_img/s" , '');
			$account_img == '' && $type != '银行卡' ? $this->error("请上传".$type."收款码") : '';
			
			$money = intval( $this->request->param("money/d" , 0) );
			$money <= 0 ? $this->error("请输入您要提现的积分") : '';
			
			if( $money > intval( $this->user_info['integral'] ) ) {
				$this->error("最多只能申请【".intval( $this->user_info['integral'] )."】积分提现");
			}
			
			//必须为整数  提现
			if( $money % 100 > 0 ) {
				$this->error("提现必须为100的倍数的整数");
			}
			
			if( $config['min_integral'] > $money ) {
				$this->error("最低提现额度为：" . $config['min_integral'] . '积分');
			}
			
			//获得配置
			$data = SettingModel::getItem('distribution');
			$cash_withdrawal = $data['cash_withdrawal'];
			//查询用户以上的配置等级数据
			$user_id = $this->user_info['user_id'];
			$user_data = [];
			for($i = 0; $i < $cash_withdrawal['level']; $i++ ) {
				$user_info = db("user")->where(['user_id' => $user_id])->field("parent_id")->find();
				if( $user_info && $user_info['parent_id'] > 0) {
					$user_data[] = $user_info['parent_id'];
					$user_id = $user_info['parent_id'];
				}else{
					break;
				}
			}
			//获得每一位的感恩奖
			$reward_price = round( $money * $cash_withdrawal['price'] / 100 );
			$total_reward_price = $reward_price * count( $user_data );
			
			$result = db('member_withdrawcash')->insert([
				'user_id' => $this->user_info['user_id'],
				'data' => json_encode($datas),
				'type' => $type,
				'cart_no' => $cart_no,
				'money' => $money,
				'account_img' => $account_img,
				'user_money' => $money - ( $cash_withdrawal['level'] * $reward_price ),
				'reward_price' => $reward_price,
				'reward_user' => $user_data ? json_encode( $user_data ) : '',
				'reward_ratio' => $cash_withdrawal['price'],
				'create_time' => time()
			]);
			
			if( $result ) {
				db("user")->where(['user_id' => $this->user_info['user_id']])->update(['integral' => $this->user_info['integral'] - $money]);
				db("user_integral_log")->insert([
					'user_id' => $this->user_info['user_id'],
					'num' => $money,
					'type' => 2,
					'content' => '申请提现扣除积分【'.$money.'】分',
					'create_time' => time()
				]);
				$this->success("提现申请成功");
			} else {
				$this->error("申请失败，请重新申请");
			}
		} else {
			$this->success("success" , ['money' => $this->user_info['integral'] , 'min_integral' => $config['min_integral'] , 'tx_blank' => (isset($config['tx_blank'])&&$config['tx_blank']?explode("\n",$config['tx_blank']):[]) , 'type_list' => ['银行卡' , '支付宝' , '微信']]);
		}
	}
	
	/**
	 * 申请提现列表
	 */
	public function withdrawcashlist() {
		$list = db('member_withdrawcash')->where(['user_id' => $this->user_info['user_id']])->order("id DESC")
				->paginate(10, false, [ 'query' => Request::instance()->request() ])->each(function($item , $key){
					$item['create_time'] = date("Y-m-d H:i" , $item['create_time']);
					unset( $item['user_id']);
					return $item;	
				})->toArray()['data'];
		return $this->renderSuccess(compact('list'));
	}
	
	/**
	 * 提现信息删除
	 */
	public function withdrawcashdel() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("信息不存在");
		$result = db("member_withdrawcash")->where(['user_id' => $this->user_info['user_id'],'id' => $id , 'status' => 1])->delete();
		if( $result ) {
			$this->success('信息删除成功');
		} else {
			$this->error("删除失败，请重试");
		}
	}
	
	
	/**
	 * 会员卡订单支付
	 */
	public function localpay() {
		$ordersn = $this->request->param("ordersn/s" , '');
		if( !$ordersn ) $this->error('订单数据错误');
		$order_info = db("member_cart_order")->where(['user_id' => $this->user_info['user_id'] , 'ordersn' => $ordersn])->find();
		if( !$order_info ) $this->error('订单信息不存在');
		if( $order_info['status'] == 1 ) {
			$this->error('订单已支付，请勿重复支付');
		}
		if( $order_info['price'] > 0 && $this->user_info['money'] >= $order_info['price'] ) {
			//扣除本地金额
			db("user")->where(['user_id' => $this->user_info['user_id']])->update(['money' => $this->user_info['money'] - $order_info['price']]);
			//写入日志
			db("user_money_log")->insert([
				'user_id' => $this->user_info['user_id'],
				'num' => $order_info['price'],
				'type' => 2,
				'content' => '会员卡购买，支付【'.$order_info['ordersn'].'】订单,扣除账户余额【'.$order_info['price'].'】',
				'create_time' => time()
			]);
			//修改订单状态
			db("member_cart_order")->where(['ordersn' => $ordersn])->update(['pay_type' => 3 , 'status' => 1 , 'pay_time' => time() , 'transaction_id' => date("YmdHis") . rand(100000,999999) , 'restart' => $this->user_info['is_open_cart']]);
			//推荐奖励
			$setting = SettingModel::getItem('store');
			if( $setting['online_open_user'] == 1 ) {
				$usermodel = new UserModel;
				$usermodel->builddistribution( $ordersn );
				//团队奖励
				//$usermodel->colonelReward($this->user_info['user_id'],$order_info['id']);
				$this->success('支付成功');
			}
		} else {
			$this->error('支付余额不足');
		}
	}
	
	/**
	 * 设置-城市区域修改
	 */
	public function areasave() {
		$province = $this->request->param("province/d" , 0);
		if( $province <= 0 ) $this->error("省ID不能为空");
		
		$city = $this->request->param("city/d" , 0);
		if( $city <= 0 ) $this->error("城市ID不能为空");
		
		$area = $this->request->param("area/d" , 0);
		if( $area <= 0 ) $this->error("区域ID不能为空");
		
		db('user')->where(['user_id' => $this->user_info['user_id']])->update([
			'province' => $province,
			'city' => $city,
			'area' => $area,
			'province_name' => db('region')->where(['id' => $province])->value("name"),
			'city_name' => db('region')->where(['id' => $city])->value("name"),
			'area_name' => db('region')->where(['id' => $area])->value("name")
		]);
		$this->success('地区设置成功');
	}
	
	/**
	 * 会员卡信息
	 */
	public function membercartinfo() {
		$cart_info = [
			'user_id' => $this->user_info['user_id'],
			'cart_sn' => $this->user_info['cart_sn'],
			'service_num' => $this->user_info['service_num'],
			'baoyang_num' => $this->user_info['baoyang_num']
		];
		if( !$this->user_info['is_open_cart'] ) {
			exit(json_encode(array('code' => 416 , 'msg' => '您还未开通会员，请开通会员。')));
		}
		$this->success("success" , $cart_info);
	}
	
	
	/**
	 * 支付中心
	 */
	public function payment() {
		$config = SettingModel::getItem('store');
		$distribution = SettingModel::getItem('distribution');
		$new_blank = [];
		if( isset($config['blank']) && $config['blank'] ) {
			$blank = explode("\r\n", $config['blank']);
			foreach( $blank as $k => $v ) {
				$dd = explode("|" , $v);
				$new_blank[] = ['name' => $dd[0] , 'blank' => $dd[1] , 'blank_no' => $dd[2]];
			}
		}
		$data = thumbImgUrl([
			'list' => $new_blank,
			'alipay' => thumbImgUrl( $config['alipay'] ),
			'wechat' => thumbImgUrl( $config['wechat'] ),
			'cart_money' => $distribution['order_price'],
			'money' => $this->user_info['money'],
			'paycenter_but' => $config['paycenter_but']
		]);
		$this->success("success" , $data);
	}
	
	/**
	 * 分享
	 */
	public function share() {
		$fx_config = SettingModel::getItem('distribution');
		include( APP_PATH . 'common/library/phpqrcode/phpqrcode.php' );
		$qrcode_file = 'uploads/qrcode/'.date("Y-m-d").'/';
		$qrcode_file_img = $qrcode_file . $this->user_info['user_id'] .'.png';
		$fx_img = $qrcode_file . 'fx_' . $this->user_info['user_id'] . '.jpg';
		//判断图片是否存在
		//if( !file_exists( $qrcode_file_img ) ){
		if( !file_exists(WEB_PATH . $qrcode_file) ) mkdir( WEB_PATH . $qrcode_file , 0777 , true );
		$floag_index = ( !$this->user_info['is_open_cart'] && $this->user_info['share_code'] && isset( $fx_config['member']['open'] ) && $fx_config['member']['open'] ) || $this->user_info['is_open_cart'];
		\QRcode::png('http://'.$_SERVER['SERVER_NAME'].'/index.php?s=/index/user/register'.($floag_index ? '/share_code/'.$this->user_info['share_code'] : '' ), $qrcode_file . $this->user_info['user_id'].'.png', "L", 12.7,0); 
		//}
		if( !$floag_index ) {
			$this->user_info['share_code'] = '*******';
		}
		//if( !file_exists( WEB_PATH . $fx_img ) ) {
		$bigImgPath = WEB_PATH . "assets/default/share.jpg";
		$qCodePath = WEB_PATH . $qrcode_file_img;
		$bigImg = imagecreatefromstring(file_get_contents($bigImgPath));
		$qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));
		list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);
		imagecopymerge($bigImg, $qCodeImg, 170, 590, 0, 0, $qCodeWidth, $qCodeHight, 100);
		list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath);
		$left_data = [188,245,307,364,424,483,541];
		for( $i = 0; $i <= 6; $i++ ) {
			imagefttext($bigImg, 30, 0, $left_data[$i], 488, 0, WEB_PATH . "assets/default/font.ttf", $this->user_info['share_code'][$i]);
		}
		imagejpeg($bigImg, WEB_PATH . $fx_img);
		//}
		$result['qrcode'] = thumbImgUrl( '/' . $qrcode_file_img ) . '?v='.rand(100000,999999);
		$result['share_qrcode'] = thumbImgUrl( '/' . $fx_img ) . '?v='.rand(100000,999999);
		$result['share_logo'] = 'http://'.$_SERVER['SERVER_NAME'].'/assets/default/logo.png';
		$result['share_code'] = $this->user_info['share_code'];
		$result['share_title'] = '【'.$this->user_info['nickname'].'】邀请您加入超星润滑油';
		$result['share_desc'] = '超越自我 星润天下';
		$result['share_url'] = thumbImgUrl( '/' . $fx_img );
		$this->success("success" , $result);
	}
	
	/**
	 * 积分流通
	 */
	public function circulation() {
		$data = SettingModel::getItem('store');
		if( $data['open_circulation'] != 1 ) {
			$this->error('积分流通已关闭，非常抱歉。');
		}
		$user_id = $this->request->param("user_id/d",0);
		$user_info = [];
		if( $user_id > 0 ) {
			$user_info = thumbImgUrl( db("user")->where(['user_id' => $user_id])->field("user_id,nickname,mobile,avatar")->find() );
			if( !$user_info ) {
				$this->error('收款用户不存在！');
			}
		}
		if( request()->isPost() ) {
			$userModel = new UserModel;
			$pass = $this->request->param("pass/s" , '');
			if( !$pass ) $this->error('支付密码不能为空');
			$mobile = $this->request->param("mobile/s" , '');
			if( !$user_info && !$mobile ) $this->error("转让手机号不能为空");
			if( $mobile > 0 ) {
				$user_info = db("user")->where(['mobile' => $mobile])->field("user_id,nickname,mobile,avatar")->find();
				if( !$user_info ) {
					$this->error("收款用户不存在");
				}
			}
			if( $user_info['mobile'] == $this->user_info['mobile'] ) $this->error('不能自己给自己转让积分');
			$num = $this->request->param("integral/d",0);
			if( $num <= 0 ) $this->error("转让积分必须大于0");
			if( $this->user_info['pay_pass'] != $userModel->passmd5($pass) ) $this->error("支付密码错误");
			if( $this->user_info['integral'] < $num ) $this->error("最多只能转让【{$this->user_info['integral']}】积分");
			//扣除积分
			db("user")->where(['user_id' => $this->user_info['user_id']])->update(['integral' => $this->user_info['integral'] - $num]);
			db("user_integral_log")->insert([
				'user_id' => $this->user_info['user_id'],
				'num' => $num,
				'type' => 2,
				'content' => '转让积分给好友【'.$user_info['nickname'].'】，共计：'. $num,
				'create_time' => time()
			]);
			//增加积分
			$user_info = db("user")->where(['mobile' => $mobile])->field("user_id,nickname,mobile,avatar,integral,total_integral")->find();
			db("user")->where(['user_id' => $user_info['user_id']])->update(['integral' => $user_info['integral'] + $num , 'total_integral' => $user_info['total_integral'] + $num ]);
			db("user_integral_log")->insert([
				'user_id' => $user_info['user_id'],
				'num' => $num,
				'type' => 1,
				'content' => '您的好友【'.$this->user_info['nickname'].'】给您转让【'.$num.'】积分',
				'create_time' => time()
			]);
			$this->getui->sendToClient($user_info['user_id'] , '您有新的积分转让入账' , '您的好友【'.$this->user_info['nickname'].'】给您转让【'.$num.'】积分，详情请在个人中心查看');
			$this->success("积分转让成功");
		} else {
			include( APP_PATH . 'common/library/phpqrcode/phpqrcode.php' );
			$qrcode_file = WEB_PATH . 'uploads/qrcode/' . date("Y-m-d");
			if( !file_exists($qrcode_file) ) mkdir( $qrcode_file , 0777 , true );
			\QRcode::png('jifen_' . $this->user_info['user_id'], $qrcode_file . '/jifen_' . $this->user_info['user_id'].'.png', "H", 12, 0);
			$qrcode_url = thumbImgUrl( '/uploads/qrcode/'.date("Y-m-d").'/jifen_' . $this->user_info['user_id'] .'.png' );
			$data = ['data' => $this->user_info['integral'] , 'user_info' => $user_info?$user_info:'' , 'qrcode_url' => $qrcode_url , 'pay_pass' => $this->user_info['pay_pass']?2:1];
			$this->success("success" , $data);
		}
	}
	
	/**
	 * 查看用户信息
	 */
	public function userinfo() {
		$mobile = $this->request->param("mobile/s",'');
		$user_info = [];
		if( !$mobile ) $this->error("手机号不能为空");
		$user_info = thumbImgUrl( db("user")->where(['mobile' => $mobile])->field("nickname,mobile,avatar")->find() );
		if( !$user_info ) {
			$this->error('收款用户不存在！');
		}
		$this->success("success" , $user_info);
	}
	
	/**
	 * 积分统计
	 */
	public function integralCount() {
		$start = time();
		$end = strtotime(date("Y-m-d 00:00:01" , time()));
		$data = [
			'total' => $this->user_info['total_integral'],
			'now_num' => $this->user_info['integral'],
			'tx_num' => $this->user_info['tx_integral'],
			'day' => db("user_integral_log")->where('type = 1 and user_id = '.$this->user_info['user_id'].' and create_time >= ' . $end . ' and create_time <= ' . $start)->sum("num"),
			'day7' => db("user_integral_log")->where('type = 1 and user_id = '.$this->user_info['user_id'].' and create_time >= ' . ( $end - ( 3600 * 24 * 7 ) ) . ' and create_time <= ' . $start)->sum("num"),
			'day1m' => db("user_integral_log")->where('type = 1 and user_id = '.$this->user_info['user_id'].' and create_time >= ' . ( $end - ( 3600 * 24 * 30 ) ) . ' and create_time <= ' . $start)->sum("num"),
		];
		$this->success("success" , $data);
	}
  
  
  	/**
	 * 团队长申请
	 */
	public function shitem() {
		$userModel = new UserModel;
		$total_price = $userModel->itemPrices( $this->user_info['user_id'] );
		$config_fx = SettingModel::getItem('distribution');
		$fx_item_price = ( isset( $config_fx['item']['condition'] ) ? $config_fx['item']['condition'] * 10000 : 0 );
		if( $this->user_info['is_item'] <= 0 && $fx_item_price > 0 && $total_price > $fx_item_price ) {
			$item_info = db("member_items")->where(['user_id' => $this->user_info['user_id']])->find();
			if( $item_info && $item_info['status'] == 2 ) {
				exit(json_encode(array("code" => 423 , 'msg' => '您发起的团队长申请已通过，请勿重复申请！')));
			}
			if( request()->isPost() ) {
				$name = $this->request->param("name/s" , '');
				if( !$name ) $this->error("用户姓名不能为空");
				$mobile = $this->request->param("mobile/s" , '');
				if( !$mobile ) $this->error("联系手机号不能为空");
				$idcard = $this->request->param("idcard/s" , '');
				if( !$idcard ) $this->error("身份证号码不能为空");
				$content = $this->request->param("content/s" , '');
				if( $item_info ) {
					$res = db("member_items")->where(['user_id' => $this->user_info['user_id']])->update([
						'name' => $name,
						'mobile' => $mobile,
						'idcard' => $idcard,
						'content' => $content,
						'create_time' => time()
					]);
				} else {
					$res = db("member_items")->insert([
						'user_id' => $this->user_info['user_id'],
						'name' => $name,
						'mobile' => $mobile,
						'idcard' => $idcard,
						'content' => $content,
						'create_time' => time()
					]);
				}
				if( $res ) {
					$this->success("团队长申请提交成功");
				} else {
					$this->success("申请失败，请重新尝试！");
				}
			} else {
				$this->success("success" , $item_info);
			}
		} else {
			exit(json_encode(array("code" => 423 , 'msg' => '您未达到团队长申请的条件')));
		}
	}
	
	/**
	 * 提现账户历史记录
	 */
	public function account_list() {
		$data_list = db("member_withdrawcash")->where(['user_id' => $this->user_info['user_id']])->field("type,data,cart_no,account_img")->select();
		$new_data = [];
		if( $data_list ) {
			foreach( $data_list as $k => $v ) {
				$data = json_decode( $v['data'] , true );
				$v = array_merge( $v , $data?$data:[] );
				if( $v['type'] == '银行卡' ) {
					$v['data'] = $v['blank_name'] . '，卡号：' . $v['cart_no'];
				} else {
					$v['data'] = '账号：' . $v['cart_no'];
				}
				$v['account_img_path'] = $v['account_img'];
				$v['account_img'] = thumbImgUrl( $v['account_img'] );
				$new_data[$v['cart_no']] = $v;
			}
		}
		$this->success("success" , $new_data);
	}
}